<template>
  <el-dialog
    v-model="dialogVisible"
    title="敏感词详情"
    width="800px"
    :before-close="handleClose"
  >
    <div v-loading="loading" class="word-detail">
      <template v-if="wordInfo">
        <!-- 基本信息 -->
        <div class="detail-section">
          <h3 class="section-title">基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="敏感词ID">
              {{ wordInfo.id }}
            </el-descriptions-item>
            <el-descriptions-item label="敏感词内容">
              <el-text class="word-content" type="primary">
                {{ wordInfo.word }}
              </el-text>
            </el-descriptions-item>
            <el-descriptions-item label="类型">
              <el-tag
                :style="{
                  backgroundColor: SensitiveWordManagementUtils.getTypeColor(
                    wordInfo.type
                  ),
                  color: '#ffffff',
                  border: 'none'
                }"
              >
                {{ wordInfo.typeDescription }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="严重程度">
              <el-tag
                :style="{
                  backgroundColor:
                    SensitiveWordManagementUtils.getSeverityColor(
                      wordInfo.severity
                    ),
                  color: '#ffffff',
                  border: 'none'
                }"
              >
                {{ wordInfo.severityDescription }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="过滤模式">
              <el-tag
                :type="
                  wordInfo.filterMode === 'REPLACE' ? 'success' : 'warning'
                "
              >
                {{ wordInfo.filterModeDescription }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="替换文本">
              <span v-if="wordInfo.replacement">{{
                wordInfo.replacement
              }}</span>
              <span v-else class="text-placeholder">-</span>
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="wordInfo.status === 1 ? 'success' : 'danger'">
                {{ wordInfo.statusDescription }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="匹配次数">
              <el-text type="primary">{{ wordInfo.matchCount || 0 }}</el-text>
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 描述信息 -->
        <div v-if="wordInfo.description" class="detail-section">
          <h3 class="section-title">描述信息</h3>
          <el-card class="description-card">
            <p>{{ wordInfo.description }}</p>
          </el-card>
        </div>

        <!-- 标签信息 -->
        <div
          v-if="wordInfo.tagList && wordInfo.tagList.length > 0"
          class="detail-section"
        >
          <h3 class="section-title">标签信息</h3>
          <div class="tag-list">
            <el-tag
              v-for="tag in wordInfo.tagList"
              :key="tag"
              effect="plain"
              class="tag-item"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>

        <!-- 统计信息 -->
        <div class="detail-section">
          <h3 class="section-title">统计信息</h3>
          <el-row :gutter="16">
            <el-col :span="8">
              <el-card class="stat-item">
                <div class="stat-content">
                  <div class="stat-value">{{ wordInfo.matchCount || 0 }}</div>
                  <div class="stat-label">总匹配次数</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="stat-item">
                <div class="stat-content">
                  <div class="stat-value">
                    {{
                      wordInfo.lastMatchTime
                        ? formatDateTime(wordInfo.lastMatchTime)
                        : "-"
                    }}
                  </div>
                  <div class="stat-label">最后匹配时间</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="stat-item">
                <div class="stat-content">
                  <div class="stat-value">
                    {{ getDaysFromCreation() }}
                  </div>
                  <div class="stat-label">创建天数</div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <!-- 创建和更新信息 -->
        <div class="detail-section">
          <h3 class="section-title">操作记录</h3>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="创建人">
              {{ wordInfo.createByName }}
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ formatDateTime(wordInfo.createTime) }}
            </el-descriptions-item>
            <el-descriptions-item
              v-if="wordInfo.updateByName"
              label="最后更新人"
            >
              {{ wordInfo.updateByName }}
            </el-descriptions-item>
            <el-descriptions-item
              v-if="wordInfo.updateTime"
              label="最后更新时间"
            >
              {{ formatDateTime(wordInfo.updateTime) }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 操作按钮 -->
        <div class="detail-actions">
          <el-button type="primary" @click="handleEdit">
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button
            :type="wordInfo.status === 1 ? 'warning' : 'success'"
            @click="handleToggleStatus"
          >
            <el-icon v-if="wordInfo.status === 1"><Close /></el-icon>
            <el-icon v-else><Check /></el-icon>
            {{ wordInfo.status === 1 ? "禁用" : "启用" }}
          </el-button>
          <el-button type="info" @click="handleCopy">
            <el-icon><CopyDocument /></el-icon>
            复制
          </el-button>
          <el-button type="danger" @click="handleDelete">
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </div>
      </template>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Edit,
  Check,
  Close,
  CopyDocument,
  Delete
} from "@element-plus/icons-vue";
import {
  getSensitiveWordDetailApi,
  enableSensitiveWordApi,
  disableSensitiveWordApi,
  deleteSensitiveWordApi,
  SensitiveWordManagementUtils,
  type SensitiveWordInfo
} from "@/api/sensitive-word-management";

interface Props {
  /** 对话框可见性 */
  visible: boolean;
  /** 敏感词ID */
  wordId: number | null;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  "update:visible": [visible: boolean];
  refresh: [];
  edit: [id: number];
}>();

// 响应式数据
const loading = ref(false);
const wordInfo = ref<SensitiveWordInfo | null>(null);

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: value => emit("update:visible", value)
});

// 工具函数
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return "-";
  return new Date(dateTime).toLocaleString();
};

const getDaysFromCreation = () => {
  if (!wordInfo.value?.createTime) return "-";
  const createDate = new Date(wordInfo.value.createTime);
  const now = new Date();
  const diffTime = Math.abs(now.getTime() - createDate.getTime());
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  return `${diffDays} 天`;
};

// 加载敏感词详情
const loadWordDetail = async () => {
  if (!props.wordId) return;

  try {
    loading.value = true;
    const response = await getSensitiveWordDetailApi(props.wordId);

    if (response.code === 200 && response.data) {
      wordInfo.value = {
        ...response.data,
        tagList: SensitiveWordManagementUtils.parseTagList(response.data.tags)
      };
    } else {
      ElMessage.error(response.message || "加载敏感词详情失败");
    }
  } catch (error) {
    console.error("加载敏感词详情失败:", error);
    ElMessage.error("加载敏感词详情失败");
  } finally {
    loading.value = false;
  }
};

// 编辑
const handleEdit = () => {
  if (wordInfo.value) {
    emit("edit", wordInfo.value.id);
    handleClose();
  }
};

// 切换状态
const handleToggleStatus = async () => {
  if (!wordInfo.value) return;

  const action = wordInfo.value.status === 1 ? "禁用" : "启用";

  try {
    await ElMessageBox.confirm(`确定要${action}这个敏感词吗？`, "确认操作", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    const api =
      wordInfo.value.status === 1
        ? disableSensitiveWordApi
        : enableSensitiveWordApi;
    const response = await api(wordInfo.value.id);

    if (response.code === 200) {
      ElMessage.success(`${action}成功`);
      emit("refresh");
      await loadWordDetail(); // 重新加载详情
    } else {
      ElMessage.error(response.message || `${action}失败`);
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error(`${action}失败:`, error);
      ElMessage.error(`${action}失败`);
    }
  }
};

// 复制
const handleCopy = async () => {
  if (!wordInfo.value) return;

  try {
    await navigator.clipboard.writeText(wordInfo.value.word);
    ElMessage.success("已复制到剪贴板");
  } catch (error) {
    console.error("复制失败:", error);
    ElMessage.error("复制失败");
  }
};

// 删除
const handleDelete = async () => {
  if (!wordInfo.value) return;

  try {
    await ElMessageBox.confirm(
      `确定要删除敏感词"${wordInfo.value.word}"吗？此操作不可恢复。`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    const response = await deleteSensitiveWordApi(wordInfo.value.id);

    if (response.code === 200) {
      ElMessage.success("删除成功");
      emit("refresh");
      handleClose();
    } else {
      ElMessage.error(response.message || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false;
  wordInfo.value = null;
};

// 监听wordId变化
watch(
  () => props.wordId,
  newId => {
    if (newId && props.visible) {
      loadWordDetail();
    }
  },
  { immediate: true }
);

// 监听对话框可见性变化
watch(
  () => props.visible,
  visible => {
    if (visible && props.wordId) {
      loadWordDetail();
    }
  }
);
</script>

<style scoped>
/* 响应式设计 */
@media (width <= 768px) {
  .detail-actions {
    flex-wrap: wrap;
    justify-content: center;
  }

  .detail-actions .el-button {
    flex: 1;
    min-width: 0;
    margin: 4px;
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .section-title {
    color: #e5e7eb;
  }

  .stat-value {
    color: #e5e7eb;
  }

  .stat-label {
    color: #9ca3af;
  }

  .description-card {
    background: #374151;
  }

  .description-card p {
    color: #d1d5db;
  }

  .stat-item {
    background: #374151;
  }
}

.word-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section:last-child {
  margin-bottom: 0;
}

.section-title {
  padding-left: 12px;
  margin: 0 0 16px;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  border-left: 4px solid #409eff;
}

.word-content {
  font-family: "Courier New", monospace;
  font-size: 16px;
  font-weight: 600;
}

.text-placeholder {
  font-style: italic;
  color: #c0c4cc;
}

.description-card {
  background: #f8f9fa;
  border: none;
}

.description-card p {
  margin: 0;
  line-height: 1.6;
  color: #666;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-item {
  margin: 0;
}

.stat-item {
  text-align: center;
  background: #f8f9fa;
  border: none;
}

.stat-content {
  padding: 16px 0;
}

.stat-value {
  margin-bottom: 8px;
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.detail-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
  padding-top: 24px;
  margin-top: 24px;
  border-top: 1px solid #ebeef5;
}

.dialog-footer {
  text-align: center;
}
</style>
